use chrono::{DateTime, Local, TimeZone};
use serde::{Deserialize, Serialize};
use tauri::{Manager, tray::{TrayIconBuilder, TrayIconEvent}, menu::{MenuBuilder, MenuItem}, AppHandle};
use std::sync::{Arc, Mutex};

// 倒计时数据结构
#[derive(Serialize, Deserialize, Clone)]
struct CountdownData {
    days: i64,
    hours: i64,
    minutes: i64,
    seconds: i64,
}

// 全局状态管理
type TrayState = Arc<Mutex<Option<tauri::tray::TrayIcon>>>;

/**
 * 更新托盘菜单显示倒计时信息
 * 在托盘右键菜单中显示当前的倒计时状态
 */
#[tauri::command]
async fn update_tray_menu(app: AppHandle, countdown: CountdownData) -> Result<(), String> {
    let tray_state: tauri::State<TrayState> = app.state();
    let tray_guard = tray_state.lock().map_err(|e| e.to_string())?;
    
    if let Some(tray) = tray_guard.as_ref() {
        // 格式化倒计时显示文本
        let countdown_text = if countdown.days > 0 {
            format!("倒计时: {}天 {:02}:{:02}:{:02}", countdown.days, countdown.hours, countdown.minutes, countdown.seconds)
        } else if countdown.hours > 0 {
            format!("倒计时: {:02}:{:02}:{:02}", countdown.hours, countdown.minutes, countdown.seconds)
        } else {
            format!("倒计时: {:02}:{:02}", countdown.minutes, countdown.seconds)
        };
        
        // 创建新的菜单项
        let countdown_item = MenuItem::with_id(&app, "countdown", &countdown_text, false, None::<&str>)
            .map_err(|e| e.to_string())?;
        let show = MenuItem::with_id(&app, "show", "显示窗口", true, None::<&str>)
            .map_err(|e| e.to_string())?;
        let hide = MenuItem::with_id(&app, "hide", "隐藏窗口", true, None::<&str>)
            .map_err(|e| e.to_string())?;
        let quit = MenuItem::with_id(&app, "quit", "退出", true, None::<&str>)
            .map_err(|e| e.to_string())?;
        
        let menu = MenuBuilder::new(&app)
            .items(&[&countdown_item, &show, &hide, &quit])
            .build()
            .map_err(|e| e.to_string())?;
            
        tray.set_menu(Some(menu)).map_err(|e| e.to_string())?;
    }
    
    Ok(())
}

// 更新窗口标题命令
#[tauri::command]
async fn update_title(window: tauri::Window, title: String) -> Result<(), String> {
    window.set_title(&title).map_err(|e| e.to_string())
}

// 设置任务栏标题命令
#[tauri::command]
async fn set_taskbar_title(window: tauri::Window, title: String) -> Result<(), String> {
    window.set_title(&title).map_err(|e| e.to_string())
}

// 隐藏窗口命令
#[tauri::command]
async fn hide_window(window: tauri::Window) -> Result<(), String> {
    window.hide().map_err(|e| e.to_string())
}

// 显示窗口命令
#[tauri::command]
async fn show_window(window: tauri::Window) -> Result<(), String> {
    window.show().map_err(|e| e.to_string())
}

// 计算倒计时命令
#[tauri::command]
fn calculate_countdown(target_date: String) -> Result<CountdownData, String> {
    // 尝试多种日期格式解析
    let target: DateTime<Local> = if let Ok(dt) = DateTime::parse_from_rfc3339(&target_date) {
        dt.with_timezone(&Local)
    } else if let Ok(dt) = DateTime::parse_from_str(&target_date, "%Y-%m-%d %H:%M:%S %z") {
        dt.with_timezone(&Local)
    } else if let Ok(naive_dt) = chrono::NaiveDateTime::parse_from_str(&target_date, "%Y-%m-%d %H:%M:%S") {
        // 如果没有时区信息，假设为本地时区
        Local.from_local_datetime(&naive_dt).single()
            .ok_or("无法解析日期时间")?
    } else {
        return Err(format!("无法解析日期格式: {}", target_date));
    };
    
    let now = Local::now();
    let diff = target.signed_duration_since(now);
    
    let total_seconds = diff.num_seconds();
    if total_seconds <= 0 {
        return Ok(CountdownData {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0,
        });
    }
    
    let days = total_seconds / (24 * 60 * 60);
    let hours = (total_seconds % (24 * 60 * 60)) / (60 * 60);
    let minutes = (total_seconds % (60 * 60)) / 60;
    let seconds = total_seconds % 60;
    
    Ok(CountdownData {
        days,
        hours,
        minutes,
        seconds,
    })
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            // 初始化托盘状态
            let tray_state: TrayState = Arc::new(Mutex::new(None));
            app.manage(tray_state.clone());
            
            // 创建初始托盘菜单
            let countdown_item = MenuItem::with_id(app, "countdown", "倒计时: 加载中...", false, None::<&str>)?;
            let show = MenuItem::with_id(app, "show", "显示窗口", true, None::<&str>)?;
            let hide = MenuItem::with_id(app, "hide", "隐藏窗口", true, None::<&str>)?;
            let quit = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?;
            
            let menu = MenuBuilder::new(app)
                .items(&[&countdown_item, &show, &hide, &quit])
                .build()?;

            // 创建托盘图标
            let tray = TrayIconBuilder::new()
                .menu(&menu)
                .on_menu_event(move |app, event| {
                    if let Some(window) = app.get_webview_window("main") {
                        match event.id.as_ref() {
                            "show" => {
                                let _ = window.show();
                                let _ = window.set_focus();
                            }
                            "hide" => {
                                let _ = window.hide();
                            }
                            "quit" => {
                                app.exit(0);
                            }
                            _ => {}
                        }
                    }
                })
                .on_tray_icon_event(|tray, event| {
                    if let TrayIconEvent::Click { button: tauri::tray::MouseButton::Left, .. } = event {
                        let app = tray.app_handle();
                        if let Some(window) = app.get_webview_window("main") {
                            if window.is_visible().unwrap_or(false) {
                                let _ = window.hide();
                            } else {
                                let _ = window.show();
                                let _ = window.set_focus();
                            }
                        }
                    }
                })
                .build(app)?;
                
            // 将托盘图标存储到状态中
            {
                let mut tray_guard = tray_state.lock().unwrap();
                *tray_guard = Some(tray);
            }

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            update_title,
            set_taskbar_title,
            hide_window,
            show_window,
            calculate_countdown,
            update_tray_menu
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
